package com.kotlin.novel.ui

import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.kotlin.novel.R
import com.kotlin.novel.adapter.BookListAdapter
import com.kotlin.novel.base.BaseActivity
import com.kotlin.novel.listener.RVOScrollListener
import com.kotlin.novel.model.BookModel
import com.kotlin.novel.utils.HttpUtil
import com.kotlin.novel.utils.showToast
import com.mewlxy.readlib.utlis.SpUtil
import kotlinx.android.synthetic.main.activity_search.*
import kotlinx.android.synthetic.main.layout_search_history.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import me.next.tagview.TagCloudView
import org.json.JSONObject


class SearchActivity : BaseActivity(), View.OnClickListener, TextView.OnEditorActionListener, TagCloudView.OnTagClickListener, TextWatcher {

    private var bookModels = ArrayList<BookModel>()
    private lateinit var bookListAdapter: BookListAdapter
    private var currentPage = 0
    private var totalPage = 1
    private var limit=6
    private var isLoading = false
    private var keyword = ""
    private var searchHistory = ""
    private lateinit var tags: List<String>
    override fun getLayoutResId(): Int {
        return R.layout.activity_search
    }

    override fun initView() {
        rv_search_result.layoutManager = LinearLayoutManager(this)
        et_search.setOnEditorActionListener(this)
        iv_back.setOnClickListener(this)
        tag_cloud_view.setOnTagClickListener(this)
    }

    override fun initData() {
        bookListAdapter = BookListAdapter(this, bookModels)
        rv_search_result.adapter = bookListAdapter
        rv_search_result.addOnScrollListener(object : RVOScrollListener(rv_search_result.layoutManager as LinearLayoutManager) {
            override fun loadMoreItems() {
                search(keyword, currentPage)
            }

            override fun totalPageCount(): Int {
                return totalPage
            }

            override fun isLastPage(): Boolean {
                return currentPage >= totalPage
            }

            override fun isLoading(): Boolean {
                return isLoading
            }

        })
        updateSearchHistory()

        et_search.addTextChangedListener(this)
    }

    private fun updateSearchHistory() {
        searchHistory = SpUtil.getStringValue("search_history", "")
        tags = searchHistory.trimEnd(',').split(",").toMutableList()
        if (searchHistory.isNotBlank()) {
            tag_cloud_view.setTags(tags)
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back -> {
                finish()
            }
        }
    }

    //搜索
    fun search(keyword: String, page: Int) = GlobalScope.launch(Dispatchers.Main) {

        val http = HttpUtil()
        Log.d("start is:",page.toString())
        //不能在UI线程进行请求，使用async起到后台线程，使用await获取结果
        async(Dispatchers.Default) { http.httpGET1("http://api.zhuishushenqi.com/book/fuzzy-search?query=${keyword}&start=${page}&limit=${limit}") }.await()
                .let {
                    val obj = JSONObject(it)
                    Log.d("url is:","http://api.zhuishushenqi.com/book/fuzzy-search?query=${keyword}&start=${page}&limit=${limit}")
                    currentPage+=limit
                    totalPage= obj.getString("total").toInt()
                    val listArray=obj.getJSONArray("books")
                    for (i in 0 until listArray.length()){
                        val item=listArray.getJSONObject(i)

                        val bookModel = BookModel()
                        bookModel.coverUrl = item.getString("cover").replace("%3A",":").replace("%2F","/").replace("/agent/","")
                        Log.d("result is:",bookModel.coverUrl)
                        bookModel.name = item.getString("title")
                        bookModel.url =item.getString("_id")
                        bookModel.bookAuthor =item.getString("author")
                        bookModel.desc =item.getString("shortIntro")
                        bookModel.source =item.getString("site")
                        bookModels.add(bookModel)
                        Log.d("result is:",item.getString("title"))
                    }
                    bookListAdapter.notifyDataSetChanged()
                    if (!searchHistory.contains(keyword)) {
                        searchHistory += "${keyword},"
                        SpUtil.setStringValue("search_history", searchHistory)
                        updateSearchHistory()
                    }
                    Log.d("total",totalPage.toString())

                }
    }



    //点击搜索
    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            keyword = et_search.text.toString().trim()
            if (!TextUtils.isEmpty(keyword)) {
                bookModels.clear()
                search(keyword, 0)
            } else {
                showToast("关键字不能为空")
            }
        }
        return true
    }

    //点击标签搜索
    override fun onTagClick(position: Int) {
        bookModels.clear()
        et_search.setText(tags[position])
        keyword=et_search.text.toString().trim()
        currentPage = 0
        search(tags[position], 0)
    }


    override fun afterTextChanged(s: Editable?) {
        if (s == null || s.isBlank()) {
            view_search_history.visibility = View.VISIBLE
            rv_search_result.visibility = View.GONE
        } else {
            view_search_history.visibility = View.GONE
            rv_search_result.visibility = View.VISIBLE
        }
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
    }

}